import React from 'react'
import { connect } from 'react-redux';
import './bank-bill-list.scss'
import { messages, deepFullCopy } from 'share/common';
import { Icon, message, Row, Col, Button, Spin, Popover, InputNumber } from 'antd'
import moment from 'moment'
import bankBillListService from './bank-bill-list.service';

class SplitPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      records: [],
      splitValue: [],
      saveButtonLoading: false,
      loading: false
    }
  }

  componentDidMount() {
    this.setState({
      records: this.props.records
    })
  }

  /**
   * 格式化数字
   * @param {Number} nStr 数字
   */
  addCommas = (nStr) => {
    nStr = nStr + '';
    let x = nStr.split('.');
    let x1 = x[0];
    let x2 = x.length > 1 ? '.' + x[1] : '';
    let rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }

  /**
   * 点击每块公务卡消费记录的查看明细触发
   * @param {Object} record 被点击查看明细的公务卡消费记录的整条数据
   * @param {Number} index 被点击查看明细的公务卡消费记录的这条数据的位置
   * @param {String} status 被点击查看明细的块的状态，NONE: 已拆分，ASSOCIATED: 已处理
   */
  hanldeOnViewDetails = (record, index, status) => {
    let showDetail = {
      'NONE': 'showNoneDetails',
      'ASSOCIATED': 'showAssociatedDetails'
    }
    let tempRecords = deepFullCopy(this.state.records)
    if (tempRecords[index].id === record.id) {
      if (tempRecords[index].relationList && tempRecords[index].relationList.length > 0) {
        // tempRecords[index].showDetails = !record.showDetails
        tempRecords[index][showDetail[status]] = !record[showDetail[status]]
      }
    } else {
      tempRecords.some((item, i) => {
        if (item.id === record.id) {
          if (tempRecords[i].relationList && tempRecords[i].relationList.length > 0) {
            // tempRecords[i].showDetails = !record.showDetails
            tempRecords[i][showDetail[status]] = !record[showDetail[status]]
            return true
          }
        }
      })
    }
    this.setState({
      records: tempRecords
    })
  }

  /**
   * 返回输入框的前缀
   */
  RenderInputPrefix = ({ record }) => {
    return (
      <div className={'prefixContainer'}>
        {record.oriCurCod}
        <div className={'prefixIcons'}>
          <Icon type="up" />
          <Icon type="down" />
        </div>
      </div>
    )
  }

  /**
   * 增加拆分输入框
   */
  handleOnAddInput = (record, index) => {
    let tempRecords = deepFullCopy(this.state.records)
    if (tempRecords[index].id === record.id) {
      tempRecords[index].inputs = record.inputs.concat([{ value: 0.00 }])
    } else {
      tempRecords.some((item, i) => {
        if (item.id === record.id) {
          tempRecords[i].inputs = record.inputs.concat([{ value: 0.00 }])
          return true
        }
      })
    }
    this.setState({
      records: tempRecords
    })
  }

  /**
   * 删除拆分输入框
   * @param {Object} record
   * @param {Number} recordIndex
   * @param {Number} inputIndex
   */
  handleOnDeleteInput = (record, recordIndex, inputIndex) => {
    let tempRecords = deepFullCopy(this.state.records)
    if (tempRecords[recordIndex].id === record.id) {
      tempRecords[recordIndex].inputs[inputIndex] = null
    } else {
      tempRecords.some((item, i) => {
        if (item.id === record.id) {
          tempRecords[i].inputs[inputIndex] = null
          return true
        }
      })
    }
    let resultRecords = tempRecords.map((record, i) => {
      let tempInput = record.inputs.filter((input) => input)
      record.inputs = tempInput
      return record
    })
    this.setState({
      records: resultRecords
    })
  }

  /**
   * 输入带拆分金额时触发，控制输入只能是数字
   * @param {Number} val
   * @param {Object} record
   * @param {Number} inputIndex
   * @param {Number} recordIndex
   */
  handleOnRecordChange = (val, record, inputIndex, recordIndex) => {
    let tempRecords = deepFullCopy(this.state.records)
    let  value = String(val);
    const reg = /^-?[0-9]*(\.[0-9]{0,2})?$/;
    if ((!isNaN(Number(value)) && reg.test(value)) || value === '' || value === '-') {
      if (Number(value) >= 0) {
        if (tempRecords[recordIndex].id === record.id) {
          tempRecords[recordIndex].inputs[inputIndex].value = value
        } else {
          tempRecords.some((item) => {
            if (item.id === record.id) {
              tempRecords[recordIndex].inputs[inputIndex].value = value
              return true
            }
          })
        }
        this.setState({
          records: tempRecords
        })
      }
    } else {
      this.setState({
        records: deepFullCopy(this.state.records)
      })
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.records) {
      let res = nextProps.records.map((item) => {
        item.inputs = []
        return item
      })
      this.setState({
        records: res
      })
    }
  }

  handleOnClose = () => {
    this.setState({
      loading: false,
      saveButtonLoading: false
    }, () => {
      this.props.hideSlide('split')
    })
  }

  /**
   * 点击保存按钮，进行公务卡消费记录拆分
   */
  handleOnSaveSplit = async () => {
    this.setState({
      saveButtonLoading: true
    }, async () => {
      let tempRecords = deepFullCopy(this.state.records)
      let splitArr = []
      let errorFlag = false
      tempRecords.some((record, index) => {
        if (typeof record.oriCurAmt !== 'number' || typeof record.posCurAmt !== 'number') {
          errorFlag = true
          message.error('总金额获取失败导致汇率计算出错')
          return true
        }
        const rate = record.oriCurAmt / record.posCurAmt // 币种汇率
        if (rate === NaN) {
          errorFlag = true
          message.error('汇率计算出错')
          return true
        }
        let total = 0 // 原币金额总和
        let totalPos = 0 // 入账金额总和，“CNY”
        let errFlag = false
        record.inputs.some((input, index) => {
          if (input.value && input.value.length > 0) {
            let obj = {}
            obj.atlBankTransactionId = record.id
            let oriAmount = Number(input.value) // 每笔拆分的原币金额
            let amount = 0 // 每笔拆分的入账金额
            if (typeof(oriAmount / rate) !== 'number') {
              errFlag = true
              return true
            }
            if (typeof(oriAmount / rate) === 'number' && (oriAmount / rate) !== NaN) {
              amount = Number((oriAmount / rate).toFixed(2))
            }
            if (amount !== NaN && oriAmount !== NaN) {
              total = total + oriAmount
              totalPos = totalPos + amount
              obj.amount = amount
              obj.oriAmount = oriAmount
              obj.oriCod = record.oriCurCod
              splitArr.push(obj)
            }
          }
        })
        if (errFlag) {
          errorFlag = true
          message.error('拆分金额汇率计算出错')
          return true
        }
        if (total === 0) {
          // errorFlag = true
          // message.error(messages('mcd.myAccount.publicServiceCardBankBill.totalEqualZero')) // 拆分金额必须大于0。
          // return true
          this.props.resetListPage()
        }
        if (total > record.oriRemainAmt) {
          message.error(messages('mcd.myAccount.publicServiceCardBankBill.splitTotalTooMuch')) // 待拆分金额大于剩余总拆分金额，请重新输入。
          errorFlag = true
          return true
        }
        const diffPos = totalPos - record.remainAmt
        const diffOri = total - record.oriRemainAmt
        /**
         * 由于原币和入账金额是通过汇率计算出来的，可能会有误差
         * 1、diffPos 和 diffOri中有且只有一个为0，那就要调整用户输入的数据，让二者都为0
         * 2、如果diffPos和diffOri一正一负，也要调整，让二者都为0
         */
        if ((diffPos*diffOri < 0) || ((diffPos + diffOri !== 0) && (diffPos*diffOri === 0))) {
          // 拆分数组(splitArr)的最大一笔拆分记录用来调整
          splitArr.sort((objA, objB) => objA.oriAmount <= objB.oriAmount ? -1 : 1)
          splitArr[splitArr.length - 1].amount = splitArr[splitArr.length - 1].amount - diffPos
          splitArr[splitArr.length - 1].oriAmount = splitArr[splitArr.length - 1].oriAmount - diffOri
        }
      })
      if (errorFlag) {
        this.setState({
          saveButtonLoading: false
        })
        return false
      }
      if (splitArr.length === 0) {
        // message.error(messages('mcd.myAccount.publicServiceCardBankBill.inputsEmpty')) // 请输入要拆分的金额
        this.setState({
          saveButtonLoading: false
        })
        return true
      }
      let res = await bankBillListService.splitRecord(splitArr)
      if (res.status === 200) {
        message.success(messages('mcd.myAccount.publicServiceCardBankBill.splitSuccess')) // 拆分成功
        this.setState({
          saveButtonLoading: false
        })
        this.props.resetListPage()
      }
    })
  }

  /**
   * 删除已拆分的记录
   */
  handleOnDeleteSplit = async (relationItem, record) => {
    let tempRecords = deepFullCopy(this.state.records)
    let res = await bankBillListService.deleteSplit({ ids: [relationItem.id] })
    if (res.status === 200) {
      let deletedRecordRes = await bankBillListService.getRecordsByIds([record.id])
      if (deletedRecordRes.status === 200) {
        tempRecords.some((item, recordIndex) => {
          if (item.id === record.id) {
            tempRecords[recordIndex].relationList = deletedRecordRes.data[0].relationList || []
            tempRecords[recordIndex].relationMap = deletedRecordRes.data[0].relationMap || {}
            tempRecords[recordIndex].posCurAmt = deletedRecordRes.data[0].posCurAmt
            tempRecords[recordIndex].splitedAmt = deletedRecordRes.data[0].splitedAmt
            tempRecords[recordIndex].remainAmt = deletedRecordRes.data[0].remainAmt
            tempRecords[recordIndex].associatedAmt = deletedRecordRes.data[0].associatedAmt
            tempRecords[recordIndex].oriCurAmt = deletedRecordRes.data[0].oriCurAmt
            tempRecords[recordIndex].oriSplitedAmt = deletedRecordRes.data[0].oriSplitedAmt
            tempRecords[recordIndex].oriRemainAmt = deletedRecordRes.data[0].oriRemainAmt
            tempRecords[recordIndex].oriAssociatedAmt = deletedRecordRes.data[0].oriAssociatedAmt
            return true
          }
        })
        this.setState({
          records: tempRecords,
          loading: false
        })
      }
    }
  }


  /**
   * 返回已拆分金额、已处理金额的有查看明细按钮那一行
   * @param {String} status 状态：已拆分: NONE、已处理: ASSOCIATED
   * @param {Number} amt 金额
   * @param {String} oriCurCod 原币种
   */
  renderDifferentStatusRecordsHead = (status, oriCurCod, amt = 0, posCurCod, posAmt, relationList, index, record) => {
    const headStatusTextObj = {
      'NONE': messages('mcd.myAccount.publicServiceCardBankBill.splitedAmt'), /** 已拆分金额 */
      'ASSOCIATED': messages('mcd.myAccount.publicServiceCardBankBill.associatedAmt') /** 已处理金额 */
    }
    const showDetail = {
      'NONE': 'showNoneDetails',
      'ASSOCIATED': 'showAssociatedDetails'
    }
    const classNameObj = {
      'NONE': 'contentHeadNONE',
      'ASSOCIATED': 'contentHeadASSOCIATED'
    }
    const className = `contentHead ${classNameObj[status]}`
    return (
      <div className={className} style={{ marginTop: status !== 'NONE' ? '17px' : '0px' }}>
        <span className={'contentHeadText'}>{headStatusTextObj[status]}：</span>
        {oriCurCod === posCurCod ?
        posCurCod
        +' '+this.addCommas(Number(posAmt || '0').toFixed(2))
        :oriCurCod+' '+this.addCommas(Number(amt || '0').toFixed(2))+' / '
        +posCurCod+this.addCommas(Number(posAmt || '0').toFixed(2))
        }
        {/* <span className={'contentHeadText'}>{oriCurCod}</span>
        <span className={'contentHeadText'}>{this.addCommas(Number(amt || '0').toFixed(2))}</span>
        <span style={{ marginRight: '4px' }}>/</span>
        <span className={'contentHeadText'}>{posCurCod}</span>
        <span className={'contentHeadText'}>{this.addCommas(Number(posAmt || '0').toFixed(2))}</span> */}
        {(relationList && relationList.length > 0) ? record[showDetail[status]] ?
          <Icon
            onClick={() => this.hanldeOnViewDetails(record, index, status)}
            className={'viewDetails'}
            type="up-circle-o"
          /> :
          <Icon
            onClick={() => this.hanldeOnViewDetails(record, index, status)}
            className={'viewDetails'}
            type="down-circle-o"
          /> : null}
        {(relationList && relationList.length > 0) ?
          <span
            onClick={() => this.hanldeOnViewDetails(record, index, status)}
            className={'viewDetails'}
          >
            {messages('mcd.myAccount.publicServiceCardBankBill.viewDetails')/** 查看明细 */}
          </span> : null
        }
      </div>
    )
  }

  /**
   * 返回已拆分或已处理金额
   * @param {Object} relationList 金额数据数组
   * @param {String} status 状态：已拆分: NONE、已处理: ASSOCIATED
   * @param {Object} record 一块公务卡消费
   */
  renderDifferentStatusRecordsDetails = (relationList, status, record) => {
    let textObj = {
      'NONE': messages('mcd.myAccount.publicServiceCardBankBill.splitAmt'), /** 拆分金额 */
      'ASSOCIATED': messages('mcd.myAccount.publicServiceCardBankBill.associatAmt'), /** 处理金额 */
    }
    return relationList.map((item) => {
      return (
        <div className={'detailLine'}>
          <div className={'part'} style={{ flex: 2 }}>
            <span className={'label'}>{textObj[status]}：</span>
            <span className={'value'}>{record.oriCurCod} </span>
            <span className={'value'}>{this.addCommas(Number(item.oriAmount || '0').toFixed(2))}</span>
          </div>
          <div className={'part'} style={{ flex: 2 }}>
            <span className={'label'}>入账金额：</span>
            <span className={'value'}>{record.posCurCod} </span>
            <span className={'value'}>{this.addCommas(Number(item.amount || '0').toFixed(2))}</span>
          </div>
          <div className={'part'}>
            <span className={'label'}>{messages('mcd.myAccount.publicServiceCardBankBill.splitStatus')/** 状态 */}：</span>
            <span className={'value status'}>{item.status}</span>
          </div>
          <div className={'part'}>
            {status === 'NONE' && <span className={'label'}>{messages('mcd.myAccount.publicServiceCardBankBill.splitAction')/** 操作 */}：</span>}
            {status === 'NONE' && <span onClick={() => {
              this.setState({
                loading: true
              }, () => {
                this.handleOnDeleteSplit(item, record)
              })
            }}
              className={'deleteAction'}
            >
              <Icon style={{ marginRight: '3px' }} type="delete" />
              {messages('common.delete') /** 删除 */}
            </span>
            }
          </div>
        </div>
      )
    })
  }
  render() {
    const { records, loading } = this.state
    const { RenderInputPrefix } = this
    return (
      <div>
        <Spin spinning={loading}>
          {records.map((record, index) => {
            let relationMap = record.relationMap || {}
            let LOANBILL = relationMap.LOANBILL || []
            let INVOICE = relationMap.INVOICE || []
            let NONE = relationMap.NONE || []
            record.ASSOCIATED = LOANBILL.concat(INVOICE)
            record.NONE = NONE
            const oriSplitedAmt = record.oriSplitedAmt || 0
            const oriAssociatedAmt = record.oriAssociatedAmt || 0
            const posSplitedAmt = record.splitedAmt || 0
            const posAssociatedAmt = record.associatedAmt || 0
            const realOriSplitedAmt = oriSplitedAmt - oriAssociatedAmt
            const realPosSplitedAmt = posSplitedAmt - posAssociatedAmt
            return (
              <div className={'splitBlock'}>
                <div
                  className={'blockHead'}
                  style={{
                    textOverflow: 'ellipsis',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap'
                  }}
                >
                <span className={'headText'}>交易金额：</span>
                  <span className={'headText'}>{record.oriCurCod}</span>
                  <span className={'headText'}>{this.addCommas(Number(record.oriCurAmt || '0').toFixed(2))}</span>
                  <br />
                  {/* <span style={{ marginRight: '5px', marginLeft: '5px' }}>|</span> */}
                  <span className={'headText'}>入账金额：</span>
                  <span className={'headText'}>{record.posCurCod}</span>
                  <span className={'headText'}>{this.addCommas(Number(record.posCurAmt || '0').toFixed(2))}</span>
                  <br />
                  <span className={'headText'}>{messages('mcd.myAccount.publicServiceCardBankBill.acpName')/** 交易摘要 */}：</span>
                  <Popover content={record.acpName}>
                    <span className={'headText'}>{record.acpName}</span>
                  </Popover>
                  <br />
                  <span className={'headText'}>交易日期：</span>
                  <span className={'headText'}>{ record.trsDate ? moment(record.trsDate).format('YYYY-MM-DD') : '-' }</span>
                </div>
                <div className={'blockContent'}>
                  {this.renderDifferentStatusRecordsHead('NONE', record.oriCurCod, realOriSplitedAmt, record.posCurCod, realPosSplitedAmt, record.NONE, index, record)}
                  {record.showNoneDetails && this.renderDifferentStatusRecordsDetails(record.NONE, 'NONE', record)}
                  {this.renderDifferentStatusRecordsHead('ASSOCIATED', record.oriCurCod, record.oriAssociatedAmt, record.posCurCod, record.associatedAmt, record.ASSOCIATED, index, record)}
                  {record.showAssociatedDetails && this.renderDifferentStatusRecordsDetails(record.ASSOCIATED, 'ASSOCIATED', record)}
                  <div className={'contentHead bottom contentHeadNOTASSOCIATED'}>
                    <span className={'contentHeadText'}>{messages('mcd.myAccount.publicServiceCardBankBill.notSplitedAmt')/** 未拆分金额 */}：</span>
                    {record.oriCurCod === record.posCurCod ?
                      record.posCurCod
                      +' '+this.addCommas(Number(record.remainAmt || '0').toFixed(2))
                      :record.oriCurCod+' '+this.addCommas(Number(record.oriRemainAmt || '0').toFixed(2))+' / '
                      +record.posCurCod+this.addCommas(Number(record.remainAmt || '0').toFixed(2))
                    }
                    {/* <span className={'contentHeadText'}>{record.oriCurCod}</span>
                    <span className={'contentHeadText'}>{this.addCommas(Number(record.oriRemainAmt || '0').toFixed(2))}</span>
                    <span style={{ marginRight: '4px' }}>/</span>
                    <span className={'contentHeadText'}>{record.posCurCod}</span>
                    <span className={'contentHeadText'}>{this.addCommas(Number(record.remainAmt || '0').toFixed(2))}</span> */}
                  </div>
                </div>
                <div className={'blockFooter'}>
                  {
                    record.inputs.map((item, i) => {
                      return (
                        <Row className={'labelLine'} style={{ height: '32px', paddingLeft: '14px', marginTop: '10px' }} gutter={24}>
                          <Col
                            className={'labelContainer'}
                            style={{
                              padding: 0,
                              height: '32px',
                              lineHeight: '32px'
                            }}
                            span={5}
                          >
                            <label className={i !== 0 && 'noLabel'}>{messages('mcd.myAccount.publicServiceCardBankBill.willSplitedAmt')}：</label>
                          </Col>
                          <Col style={{ padding: 0 }} span={15}> 
                            {/* <Input
                              onChange={(e) => this.handleOnRecordChange(e, record, i, index)}
                              value={item.value}
                              style={{ height: '32px', width: '420px' }}
                              prefix={<RenderInputPrefix record={record} />}
                            /> */}
                            <span className={'prefixContainer'}>
                              {record.oriCurCod}
                              <div className={'prefixIcons'}>
                                <Icon style={{ fontSize: '10px', transform: 'scale(0.5)'}} type="up" />
                                <Icon style={{ fontSize: '10px', transform: 'scale(0.5)' }} type="down" />
                              </div>
                            </span>
                            <InputNumber
                              step={0.01}
                              precision={2}
                              onChange={(e) => this.handleOnRecordChange(e, record, i, index)}
                              formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                              parser={value => value.replace(/\$\s?|(,*)/g, '')}
                              value={item.value}
                              style={{
                                height: '32px',
                                minWidth: '100px',
                                width: 'calc(100% - 70px)',
                                borderTopLeftRadius: '0px',
                                borderBottomLeftRadius: '0px'
                              }}
                            />
                          </Col>
                          <Col
                            onClick={() => this.handleOnDeleteInput(record, index, i)}
                            style={{ padding: 0, textAlign: 'center' }}
                            className={'deleteContainer'}
                            span={4}
                          >
                            <Icon type="minus-circle" theme="filled" />
                          </Col>
                        </Row>
                      )
                    })
                  }
                  <Row className={'addContainer'} gutter={24}>
                    <Col
                      className={'labelContainer'}
                      style={{
                        padding: 0,
                        height: '32px',
                        lineHeight: '32px'
                      }}
                      span={5}
                    >
                      {record.inputs.length === 0 ? <label className={'addlabel'}>{messages('mcd.myAccount.publicServiceCardBankBill.willSplitedAmt')}：</label> : null}
                    </Col>
                    <Col style={{ padding: 0 }} span={15}>
                      <div className={'addButton'} style={{ height: '32px', width: '100%' }} onClick={() => this.handleOnAddInput(record, index)}>
                        <Icon type="plus-circle" theme="filled" />
                        <span>{messages('mcd.myAccount.publicServiceCardBankBill.addSplitAmt')}</span>
                      </div>
                    </Col>
                  </Row>
                </div>
              </div>
            )
          })}
        </Spin>
        <div className="slide-footer">
          <Button loading={this.state.saveButtonLoading} onClick={() => this.handleOnSaveSplit()} type="primary" htmlType="submit">{messages('common.save')}</Button>
          <Button onClick={() => this.handleOnClose()}>{messages('common.cancel')}</Button>
        </div>
      </div >
    )
  }
}

SplitPage.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser
  };
}
export default connect(mapStateToProps)(SplitPage);

